//
//  AdView.swift
//  CompareBuying
//
//  Created by 唐先才 on 16/2/19.
//  Copyright © 2016年 唐先才. All rights reserved.
//

import UIKit

class AdView: UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    var adView: UICollectionView?
    var pageControl: UIPageControl?
    var dataArray: NSMutableArray = []
    var timer: NSTimer?
    var adWidth: CGFloat?
    var adHeight: CGFloat?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        adWidth = frame.size.width
        adHeight = frame.size.height
        self.createAdView()
        self.createPageControl()
        self.createTimer()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    func configWithArray(dataArray: NSMutableArray) {
        self.dataArray = dataArray
        guard let adView = self.adView else {
            print("刷新失败")
            return
        }
        adView.reloadData()
        adView.scrollToItemAtIndexPath(NSIndexPath.init(forItem: 0, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
//        let currentIndexPath = adView.indexPathsForVisibleItems().last
//        guard let newCurrentIndexPath = currentIndexPath else {
//            return
//        }
//        let nextItem = newCurrentIndexPath.item + 1
//        let nextSection = newCurrentIndexPath.section
//        let nextIndexPath = NSIndexPath.init(forItem: nextItem, inSection: nextSection)
//        adView.scrollToItemAtIndexPath(nextIndexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    
    func createAdView() {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .Horizontal
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        guard let adWidth = self.adWidth, adHeight = self.adHeight else {
            return
        }
        layout.itemSize = CGSizeMake(adWidth, adHeight)
        
        let adRect: CGRect = CGRectMake(0, 0, adWidth, adHeight)
        adView = UICollectionView(frame: adRect, collectionViewLayout: layout)
        guard let adView = self.adView else {
            print("创建collectionView失败")
            return
        }
        adView.delegate = self
        adView.dataSource = self
        adView.pagingEnabled = true
        adView.showsHorizontalScrollIndicator = false
        adView.showsVerticalScrollIndicator = false
        adView.backgroundColor = UIColor.whiteColor()
        self.addSubview(adView)
        
        let nib = UINib(nibName: "RollingCell", bundle: NSBundle.mainBundle())
        adView.registerNib(nib, forCellWithReuseIdentifier: "rollingCell")
    }
    
    func createPageControl() {
        pageControl = UIPageControl()
        guard let pageControl = self.pageControl, adHeight = self.adHeight else {
            print("创建pageControl失败")
            return
        }
        pageControl.center = CGPointMake(self.frame.size.width * 0.5, adHeight - 20)
//        pageControl.frame = CGRectMake(adWidth! * 0.25, adHeight - 20, self.frame.size.width * 0.5, 20)
        pageControl.backgroundColor = UIColor.yellowColor()
        pageControl.bounds = CGRectMake(0, 0, 100, 0)
        pageControl.numberOfPages = self.dataArray.count
        pageControl.pageIndicatorTintColor = UIColor.blueColor()
        pageControl.currentPageIndicatorTintColor = UIColor.redColor()
        self.addSubview(pageControl)
    }
    
    func createTimer() {
        timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "runLoop", userInfo: nil, repeats: true)
        guard let timer = self.timer else {
            print("创建定时器失败")
            return
        }
        NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
    }
    
    func removeTimer() {
        guard let timer = self.timer else {
            print("定时器移除失败")
            return
        }
        timer.invalidate()
    }
    
    /*
    下一个广告
    */
    func runLoop() {
        guard let adView = self.adView, adWidth = self.adWidth else {
            print("下一个广告失败")
            return
        }
        let offset = adView.contentOffset.x + adWidth
        adView.setContentOffset(CGPointMake(offset, 0), animated: true)
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataArray.count * 1000
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        if let rollingCell = collectionView.dequeueReusableCellWithReuseIdentifier("rollingCell", forIndexPath: indexPath) as? RollingCell {
            if self.dataArray.count > 0 {
                if let model = self.dataArray[indexPath.item % self.dataArray.count] as? TxcModel {
                    rollingCell.configCellWithModel(model)
                }
            }
            return rollingCell
        }
        return UICollectionViewCell()
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        guard let adWidth = adWidth, adHeight = adHeight else {
            return CGSizeZero
        }
        return CGSizeMake(adWidth, adHeight)
    }
    
//    func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
//        let visiablePath = collectionView.indexPathsForVisibleItems().first
//        guard let vp = visiablePath, pageControl = self.pageControl else {
//            print("获取当前可见的单元格失败")
//            return
//        }
//        pageControl.currentPage = vp.item % self.dataArray.count
//    }
    
    /*
    拖拽时暂时销毁定时器
    */
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.removeTimer()
    }
    
    /*
    停止拖拽时再次定时器
    */
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        self.createTimer()
    }
}
